package com.steven.ourcontest.me.api

import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.me.bean.UsersDetailsRes
import com.steven.ourcontest.net.BaseResponse
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.NetConstants
import io.reactivex.Observable
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class MeApi private constructor() {
    private val mRetrofit: Retrofit
    private val mApiService: MeApiService

    companion object {
        const val DEFAULT_TIMEOUT = 10
        val instance: MeApi by lazy {
            MeApi()
        }
    }

    init {
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(
            DEFAULT_TIMEOUT.toLong(),
            TimeUnit.SECONDS
        )
        builder.addInterceptor {
            val request = it.request()
            val requestBuilder = request.newBuilder()
            requestBuilder.header("uid", LoginController.userId.toString())
                .header("userType", LoginController.userType)
            return@addInterceptor it.proceed(requestBuilder.build())
        }
        mRetrofit = Retrofit.Builder()
            .client(builder.build())
            .baseUrl(NetConstants.IMAGE_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        mApiService = mRetrofit.create(MeApiService::class.java)
    }


    fun uploadIcon(body: RequestBody): Observable<BaseResponse<EmptyResponse>> {
        return mApiService.uploadIcon(body)
    }

    fun querySelfUrl(): Observable<BaseResponse<UsersDetailsRes>> {
        return mApiService.querySelfUrl()
    }
}